<?php

session_start();

if(!isset($_SESSION['username'])){
    header("Location: login.php");
}

// 接收前端传递过来的参数
$op = '';
if(isset($_REQUEST['operation'])){
    $op = $_REQUEST['operation'];
}
if($op==""){
    die("You must sepcify an operation!");
}

if($op=="new" || $op=="update"){
    $name = isset($_POST['name']) ? trim($_POST['name']) : "";
    $gender = isset($_POST["gender"]) ? trim($_POST["gender"]) : "";
    $dob = isset($_POST["dob"]) ? trim($_POST["dob"]) : "";
    $phone = isset($_POST["phone"]) ? trim($_POST["phone"]) : "";
    $email = isset($_POST["email"]) ? trim($_POST["email"]) : "";
    $avatar = isset($_POST["avatar"]) ? trim($_POST["avatar"]) : "";
    // echo "<pre>";
    // print_r($_FILES);
    // echo "</pre>";
    // die("end");

    $errors = [];
    $file = null;

    // 数据有效性验证

    if (isset($_FILES['avatar']) && is_uploaded_file($_FILES['avatar']['tmp_name'])) {
        $file = $_FILES['avatar'];
        $file_type = $file['type']; // $_FILES['avatar']['type']
        $file_error = $file['error'];
        if (!($file_type == "image/jpeg" || $file_type == "image/png")) {
            $errors[] = "图片只接收 jpeg 或 png 类型的文件。";
        }
        if ($file_error == 1) {
            $errors[] = "图片超过 php.ini 配置文件允许的大小。";
        }
        if ($file_error == 2) {
            $errors[] = "图片超过了MAX_FILE_SIZE选项指定的大小。";
        }
        if ($file_error == 3) {
            $errors[] = "图片内容上传不完整。";
        }
        if ($file_error == 4) {
            $errors[] = "图片文件未能上传。";
        }
        if ($file_error == 5) {
            $errors[] = "图片文件大小为0。";
        }
    }
    
    if($op=="update"){
        $id = isset($_POST['id']) ? $_POST["id"] : "";
        if($id==""){
            $errors[] = "必须传递记录 ID！";
        }
    }
 
    if ($name == "") {
        $errors[] = "姓名不能为空！";
    }
    if (filter_var($gender, FILTER_VALIDATE_INT) === false) {
        $errors[] = "性别的值不合法！";
    }

    // "2010-12-31"
    $date_array = [];
    $date_of_birth = null;
    if ($dob !== "") {
        $date_array = explode("-", $dob); //["2010","12","31"];
        // var_dump($date_array);
    }
    if (count($date_array) == 3) {
        if (checkdate($date_array[1] + 0, $date_array[2] + 0, $date_array[0] + 0) === false) {
            $errors[] = "日期的值不合法！";
        } else {
            $date_of_birth = $dob;
        }
    }
    if ($phone == "") {
        $errors[] = "必须输入电话！";
    }
    if ($email !== "") {
        if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
            $errors[] = "电邮格式错误！";

        }
    }

    if (count($errors) > 0) {
        var_dump($errors);
        die("");
        // 数据校验有错，返回“添加联系人”界面并且显示错误信息
    }
    // 存入数据库

    $db = null;

    require "db.php";

    if ($db == null) {
        die("无法连接数据库！");
    }
}

if($op=="new"){
    $ins = "insert into contacts(name,gender,dob,phone,email) values(?,?,?,?,?)";
    $stmt = $db->prepare($ins);
    $stmt->bindValue(1, $name);
    $stmt->bindValue(2, ($gender + 0));
    $stmt->bindValue(3, $date_of_birth);
    $stmt->bindValue(4, $phone);
    $stmt->bindValue(5, $email);
    $stmt->execute();
    $lastId = $db->lastInsertId();
    if ($lastId) {
        //插入成功
        if ($file !== null) {
            // sdfvwuyeg.123.jpg
            $name_arr = explode(".",$file['name']); 
            $ext =  $name_arr[count($name_arr)-1];
            move_uploaded_file($file['tmp_name'], "avatars/" . $lastId . '.' . $ext);
        }
        $_SESSION['info'] = "记录已经成功添加！";
        header("Location:index.php");
    } else {
        print_r($stmt->errorInfo());
        die();
        // 插入失败
        header("Location:new-contact.php");
    }
}

if($op=="update"){
    $update = "update contacts set name=?, gender=?, dob=?, phone=?, email=? where id=?";
    $stmt = $db->prepare($update);
    $stmt->bindValue(1, $name);
    $stmt->bindValue(2, ($gender + 0));
    $stmt->bindValue(3, $date_of_birth);
    $stmt->bindValue(4, $phone);
    $stmt->bindValue(5, $email);
    $stmt->bindValue(6, $id);
    $rowCount = $stmt->execute();
    if ($rowCount==1) {
        //修改成功
        if ($file !== null) {
            // sdfvwuyeg.123.jpg
            $name_arr = explode(".",$file['name']); 
            $ext =  $name_arr[count($name_arr)-1];
            move_uploaded_file($file['tmp_name'], "avatars/" . $id . '.' . $ext);
        }
        $_SESSION['info'] = "记录已经成功修改！";
        header("Location:index.php");
    } else {
        print_r($stmt->errorInfo());
        die();
        // 插入失败
        header("Location:edit-contact.php?id=$id");
    }
}

if($op=="delete"){
    $id = isset($_GET['id']) ? $_GET["id"] : "";
    if($id==""){
        die("必须传递记录 ID！");
    } 
    require "db.php";

    if ($db == null) {
        die("无法连接数据库！");
    }
    $rowCount = $db->exec("delete from contacts where id=$id");
    if ($rowCount==1) {
        //删除成功
        if(file_exists("avatars/${id}.jpg")){
            unlink("avatars/${id}.jpg");
        }
        if(file_exists("avatars/${id}.png")){
            unlink("avatars/${id}.png");
        }
        $_SESSION['info'] = "编号为 $id 的记录已经成功删除！";
        header("Location:index.php");
    } else {
        
        die("删除失败！");
        // 插入失败
        // header("Location:index.php");
    }

}

// 返回首页